const util = require('util.js')
import global from '../config/index'
import { ACCESS_TOKEN } from './types';

const config = {
  api_base_url: `${global.http}`,
  appkey:'',
}

var num = 0;
var timers = null;

class HTTP {
  // 网络请求函数
  request(params) {

    if(params.url != '/app/login/client'){
      // timers = setTimeout(() => {
      //   if(num > 0){
      //     console.log('1112333')
          
      //   }
      // }, 800)
      // wx.showLoading({
      //   title: '加载中',
      // });
    }
  
    return new Promise((resolve,rejects)=>{
      this._request(params,resolve,rejects)
    })
  }
  _request(params,resolve,rejects){
    let url = params.url.substring(0,5) == 'https' ? params.url : (config.api_base_url + params.url)
    var token = wx.getStorageSync(ACCESS_TOKEN);
    num++;
    // var headers = token ? {
    //   'auth-token':wx.getStorageSync('token')
    // } : {};
    params.method = params.method ? params.method : 'post';
    console.log(params,'params')
    var timeStamp = new Date().getTime();
    if(params.headers && params.headers.file){
      params.data.append('timeStamp',timeStamp)
      params.data.append(ACCESS_TOKEN,token)
    }else{
      if ((token) && params.url != '/app/login/client') {
        var data = {};
        for (const key in params.data) {
          if (params.data.hasOwnProperty(key) && params.data[key] !==  null && params.data[key] !==  undefined && params.data[key] != '') {
            data[key] = params.data[key]
          }
        }
        var tokenObj = new Object()
        tokenObj[ACCESS_TOKEN] = token
        tokenObj['timeStamp'] = timeStamp
        params.data = Object.assign(data,tokenObj)
      }
    }
    wx.request({
      url: url,
      method: params.method,
      data: params.data,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: (res) => {
        num--;
        let code = res.statusCode.toString()
        // console.log(res,'shuju')
        // 判断状态码是否以2开头
        if (code.startsWith('2')) {
          // 回调函数
          // params.success(res.data)
          // console.log(res,'ressrequest')
          if(timers){
            clearTimeout(timers);
          }
          // wx.hideLoading({noConflict: true,});
          // setTimeout(() => {
          //   wx.hideLoading();
          // }, 800)
          if(res.data.errCode == 'ERROR_TOKEN'){
            wx.hideLoading({
              noConflict: true,
              success: (res) => {
                wx.showModal({
                  title: '温馨提示',
                  content: '您的登录已经过期，请重新登录',
                  success: function(){
                    wx.redirectTo({
                      url: '/pages/Welcome/Welcome',
                    })
                  },
                })
              },
            })
          }else{
            resolve(res.data)
          }
          // else{
          //   this._show_error(res.data)
          //   resolve(res.data)
          // }
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '错误信息：'+res.data+',是否返回登录页面？',
            success: function(bool){
              if(bool.confirm){
                wx.redirectTo({
                  url: '/pages/Welcome/Welcome',
                })
              }
            },
          })
          rejects()
        }
      },
      fail: (err) => {
        this._show_error()
        rejects()
      },
      complete: function (res) {
        wx.hideLoading({
          noConflict: true,
        })
      }
    })
  }

  // 错误处理函数
  _show_error(error_code) {
    if (!error_code) {
      error_code = {
        errMessage: '网络开小车了，请稍后再试'
      }
    }
    wx.showToast({
      title: error_code.errMessage,
      icon: 'none',
      duration: 2000
    })
  }
}

export {
  HTTP
}